package dao

import (
	"fmt"
	"time"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/usersteward"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

func (d *UserDao) SetStewardWorkforceStaff(param *request.SetStewardWorkforceStaffReq) *dingo.ErrorWrap {
	db := global.Orm.Table("users_staff").Where("id=?", param.StaffId)
	db.Update("workforce_config", param.WorkforceConfig)
	return dingo.ErrorIf(db.Error)
}

// SetStewardPlaceStaff 设置网点员工
func (d *UserDao) SetStewardPlaceStaff(param *request.SetStewardPlaceStaffReq) *dingo.ErrorWrap {
	existIds := []int{0}
	existIdsMap := map[int]bool{}
	newInsertList := []map[string]interface{}{}
	ids := d.GetStewardRelevancePlaceStaffUserList(&request.StStaffListReq{PlaceId: param.PlaceId}).Unwrap().([]int)
	for _, id := range param.StaffIds {
		for _, oldId := range ids {
			if oldId == id {
				existIds = append(existIds, id)
				existIdsMap[id] = true
				break
			}
		}
		if !existIdsMap[id] {
			newInsertList = append(newInsertList, map[string]interface{}{
				"place_id":       param.PlaceId,
				"staff_id":       id,
				"handle_user_id": param.LoginUserId,
				"status":         1,
				"ip":             param.Ip,
			})
		}
	}

	db := global.Orm.Exec("DELETE FROM `places_staff` WHERE staff_id NOT IN (?) AND place_id=?", existIds, param.PlaceId)
	if len(newInsertList) == 0 || db.Error != nil {
		return dingo.ErrorIf(db.Error)
	}

	db = global.Orm.Table("places_staff").Create(&newInsertList)
	return dingo.ErrorIf(db.Error)
}

// GetStewardPlaceStaffUserList 获取网点员工
func (d *UserDao) GetStewardPlaceStaffUserList(param *request.StStaffListReq) *dingo.ErrorWrap {
	var lst []*usersteward.StUserStaff

	userIds := []int{0}
	if param.IsAdmin == helper.TypeNumIsAdminPartner {
		userIds = []int{param.LoginUserId}
	}

	fields := `us.id,role_name,name,phone,DATE_FORMAT(us.create_time,'%Y-%m-%d %T')
	create_time,DATE_FORMAT(us.login_time,'%Y-%m-%d %T')login_time`
	db := global.Orm.Table("users_staff us").Select(fields)
	db.Where("(us.parent_id=? OR us.parent_id IN ?) AND us.status=?", param.UserId, userIds, 1)

	data := d.GetStewardRelevancePlaceStaffUserList(param)
	ids := data.Unwrap().([]int)
	placeStaffUserList := data.Val().([]*usersteward.StPlacesUserStaff)
	if len(ids) > 0 {
		db.Or("us.id IN (?) AND us.status=?", ids, 1)
	}

	db.Order("us.id DESC").Find(&lst)
	for _, item := range lst {
		for _, item1 := range placeStaffUserList {
			if item.Id == item1.StaffId {
				item.Status = item1.Status
				break
			}
		}
	}
	return dingo.ErrorIf(db.Error, lst, ids)
}

// GetStewardRelevancePlaceStaffUserList 查询已关联员工
func (d *UserDao) GetStewardRelevancePlaceStaffUserList(param *request.StStaffListReq) *dingo.ErrorWrap {
	var ids []int
	var list []*usersteward.StPlacesUserStaff

	db := global.Orm.Model(&usersteward.StPlacesUserStaff{})
	db.Where("place_id = ?", param.PlaceId)
	db.Find(&list)

	for _, item := range list {
		ids = append(ids, item.StaffId)
	}

	return dingo.ErrorIf(db.Error, ids, list)
}

// GetStewardStaffUserList 获取员工列表
func (d *UserDao) GetStewardStaffUserList(param *request.StStaffListReq) *dingo.ErrorWrap {

	var (
		lst    []*request.StStaffListRes
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `us.id,us.role_name,us.status,us.name,us.phone,us.parent_id,u.user_name parent_name,us.workforce_config,
	message_types,DATE_FORMAT(create_time,'%Y-%m-%d %T')create_time,DATE_FORMAT(login_time,'%Y-%m-%d %T')login_time`
	db := global.Orm.Table("users_staff us").Select(fields)
	db.Joins("LEFT JOIN users u on us.parent_id = u.id")
	db.Where("us.status<>?", helper.TypeNumAccountsStatusDelete)

	if !helper.IsAdminAndStaff(param.IsAdmin, param.ParentId) {
		uList := NewUserDao().QueryChildUserIds(param.LoginUserId).Unwrap().([]int)
		db.Where("us.parent_id IN ?", append(uList, param.LoginUserId))
	}

	if param.StaffName != "" {
		sqlName := fmt.Sprintf(`%s%s%s`, "%", param.StaffName, "%")
		db.Where("us.name LIKE ? OR us.phone LIKE ?", sqlName, sqlName)
	}

	if param.Phone != "" {
		db.Where("us.phone = ?", param.Phone)
	}

	db.Order("us.id DESC")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// InsertStewardStaffUser 新增员帐号
func (d *UserDao) InsertStewardStaffUser(param *usersteward.StUserStaff) *dingo.ErrorWrap {
	var target usersteward.StUserStaff
	global.Orm.Model(&param).Where("phone=?", param.Phone).First(&target)
	if target.Status == helper.TypeNumAccountsStatusDelete {
		param.Id = target.Id
		//param.ParentId = target.ParentId
		return d.UpdateStewardStaffUser(param, target.Id)
	}

	sqlData := map[string]interface{}{
		"parent_id":      param.ParentId,
		"role_name":      param.RoleName,
		"name":           param.Name,
		"phone":          param.Phone,
		"icon":           param.Icon,
		"sex":            param.Sex,
		"status":         param.Status,
		"message_types":  param.MessageTypes,
		"applet_openid":  param.AppletOpenid,
		"tencent_openid": param.TencentOpenid,
		"password":       utils.EncryptPassword(param.Password),
		"message":        param.Message,
		"ip":             param.Ip,
	}

	db := global.Orm.Model(&param).Create(&sqlData)
	return dingo.ErrorIf(db.Error)
}

// UpdateStewardStaffUser 修改员工帐号
func (d *UserDao) UpdateStewardStaffUser(param *usersteward.StUserStaff, targetId int) *dingo.ErrorWrap {
	sqlData := map[string]interface{}{
		"parent_id":     param.ParentId,
		"role_name":     param.RoleName,
		"name":          param.Name,
		"phone":         param.Phone,
		"status":        param.Status,
		"message":       param.Message,
		"message_types": param.MessageTypes,
	}

	db := global.Orm.Debug().Model(&param).Where("id=?", param.Id)

	db.Updates(&sqlData)
	return dingo.ErrorIf(db.Error)
}

// DeleteStewardStaffUser 删除员工账号
func (d *UserDao) DeleteStewardStaffUser(param *usersteward.StUserStaff, IsAdmin uint8) *dingo.ErrorWrap {
	db := global.Orm.Debug().Model(&param)

	if IsAdmin == helper.TypeNumIsAdminOperator {
		db.Where("id=?", param.Id)
	} else {
		db.Where("id=? AND parent_id=?", param.Id, param.ParentId)
	}
	if db.Update("status", helper.TypeNumAccountsStatusDelete); db.Error != nil {
		return dingo.ErrorIf(db.Error)
	}

	// 更新网点关联
	return dingo.ErrorIf(global.Orm.Exec("DELETE FROM places_staff WHERE staff_id=?", param.Id).Error)
}

// GetStaffUserInfoFromPhone 查询员工信息
func (d *UserDao) GetStaffUserInfoFromPhone(phone string) *dingo.ErrorWrap {
	data := &usersteward.StUserStaff{}
	db := global.Orm.Raw("SELECT * FROM users_staff WHERE phone=?", phone).Find(&data)

	return dingo.ErrorIf(db.Error, data)
}

// UpdateStewardStaffUserById 更新员工信息
func (d *UserDao) UpdateStewardStaffUserById(m *usersteward.StUserStaff) *dingo.ErrorWrap {
	t := time.Now().Format("2006-01-02 15:04:05")
	data := map[string]interface{}{
		"login_time":     t,
		"ip":             m.Ip,
		"tencent_openid": m.TencentOpenid,
	}

	db := global.Orm.Debug().Model(&m).Where("id=?", m.Id).Updates(&data)
	global.Orm.Table("places_staff").Where("staff_id=? AND status=?", m.Id, 2).Update("status", 1)
	return dingo.ErrorIf(db.Error, true)
}

// GetStewardStaffUserInfo 获取员工详情
func (d *UserDao) GetStewardStaffUserInfo(param *request.StStaffListReq) *dingo.ErrorWrap {
	data := &request.StewardStaffUserInfoRes{}

	fields := `us.id,role_name,us.status,us.name,phone,DATE_FORMAT(create_time,'%Y-%m-%d %T')
	create_time,DATE_FORMAT(login_time,'%Y-%m-%d %T')login_time`
	db := global.Orm.Table("users_staff us").Select(fields)
	db.Where("us.status<>? AND us.id=?", helper.TypeNumAccountsStatusDelete, param.UserId)

	db.Find(&data)
	return dingo.ErrorIf(db.Error, data)
}
